#!/bin/bash

# /////////////////////////////////////////////////////////////////////
# 
# Simple EC2 server selection list for ssh connection
# - caches ec2 instances list
# - cache can be refreshed using "--refresh" command-line parameter 
#
# v0.2 - 2011-07-25
# Written by Christophe Deliens (chris@deliens.be)
#
# /////////////////////////////////////////////////////////////////////

# User-defined constants
EC2_CACHE_FILE=~/.aws/.ec2_instances
EC2_KEY_FILE=~/.ssh/cdeliens-aws.pem
SSH_USERNAME=ubuntu

function refreshInstancesCache() {
	echo
	echo "Loading ec2 instances list..."
	ec2-describe-instances --region $EC2_REGION > $EC2_CACHE_FILE
}

function buildInstancesList() {
	EC2_INSTANCES=`cat $EC2_CACHE_FILE | grep INSTANCE | cut -f 2`

	unset EC2_CHOICES
	unset EC2_HOSTNAMES

	# Creating a dummy ec2 instance for "refresh" menu option
	EC2_CHOICES[0]="Refresh ec2 instances list..."

	# Looping on instance IDs list to build one array containing the choices (labels)
	# and another containing the hostnames
	for ec2Instance in $EC2_INSTANCES; do
		ec2Hostname=`cat $EC2_CACHE_FILE | grep "$ec2Instance" | grep 'INSTANCE' | cut -f 4`
		ec2Name=`cat $EC2_CACHE_FILE | grep "$ec2Instance" | grep 'TAG' | grep 'Name' | cut -f 5`
		index=${#EC2_CHOICES[*]}
		EC2_CHOICES[$index]=`echo "$ec2Hostname - $ec2Name ($ec2Instance)"`
		EC2_HOSTNAMES[$index]=`echo $ec2Hostname`
	done
}

function outputMenu() {
	EC2_CACHE_DATE=`stat -x $EC2_CACHE_FILE | grep "Modify"`
	EC2_CACHE_DATE=${EC2_CACHE_DATE:8}
	echo	
	echo Cached instances list date: $EC2_CACHE_DATE 
	
	echo
	echo "Select the ec2 instance to connect to:"
	select dummy in "${EC2_CHOICES[@]}";
	do
		if [ $REPLY == "1" ]; then
			refreshInstancesCache
			buildInstancesList
			outputMenu
			break
		else
			hostname=${EC2_HOSTNAMES[$REPLY -1]}	
			echo 
			echo "Connecting to $hostname..."
			ssh -i $EC2_KEY_FILE $SSH_USERNAME@$hostname
			break
		fi
	done
}

# Creating cache file if it doesn't exist or if we force a refresh from command line
if [[ ! -e "$EC2_CACHE_FILE" || $@ == "--refresh" ]]; then
	refreshInstancesCache	
fi

# Building list of ec2 instance IDs
declare -a EC2_CHOICES
declare -a EC2_HOSTNAMES
buildInstancesList

# Outputting the menu
outputMenu
